<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\web\controller;

use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsCategory as GoodsCategoryModel;
use app\common\model\GoodsSpec;
use app\common\model\GoodsTag as GoodsTagModel;
use app\common\model\GoodsTagRelation as GoodsTagRelationModel;
use app\common\model\UserFavorite;
use app\api\controller\Goods as ApiGoodsController;

class Goods extends Base
{
    /**
     * 商品详情页
     */
    public function detail()
    {
        $id = $this->request->route->param('id');

        $goods = GoodsModel::where([
            'status' => 1,
            'id'     => $id
        ])->find();

        if (!$goods) {
            return $this->render('404', ['title' => trans('goods_not_exists')]);
        }

        // 获取分类信息
        $goods->cate = $goods->category;

        // 处理价格显示
        $goods->is_free = empty($goods->price) ? 1 : 0;

        // 获取付费内容信息（使用API控制器的逻辑）
        $apiController          = new ApiGoodsController();
        $apiController->user_id = $this->user_id; // 设置用户ID

        // 使用反射调用protected方法
        $reflection           = new \ReflectionClass($apiController);
        $getPaidContentMethod = $reflection->getMethod('getPaidContent');
        $getPaidContentMethod->setAccessible(true);

        $paidContentInfo          = $getPaidContentMethod->invoke($apiController, $id, $this->user_id);
        $goods->paid_content      = $paidContentInfo['content'];
        $goods->paid_content_type = $paidContentInfo['content_type'];
        $goods->has_paid          = $paidContentInfo['has_paid'] ? true : false;

        // 获取商品规格信息
        $goods->spec_info = $this->getGoodsSpecInfo($id);

        // 获取商品标签 - 参考API实现
        $goods_tags_relation = GoodsTagRelationModel::where('goods_id', $id)->column('tag_id');
        $goods->tags         = $goods_tags_relation ? GoodsTagModel::where('id', 'in', $goods_tags_relation)->field('id,name')->select() : [];


        // 获取收藏状态
        $goods->is_favorited = $this->checkFavoriteStatus($id);

        // 增加浏览量
        $this->incrementViews($id);

        // 获取相关商品
        $relatedGoods = $this->getRelatedGoods($goods->cate_id, $id, 10);

        // 获取默认评论数据（前5条，用于SEO）
        $defaultComments = $this->getDefaultComments($id);
        $comments        = $defaultComments['list'];
        $total           = $defaultComments['total'];
        $per_page        = 5;
        $current_page    = 1;
        $total_pages     = ceil($total / $per_page);
        $has_more        = $total > $per_page;

        // 使用商品的模板字段，如果为空则使用默认模板
        $template = $goods->template ?: 'goods/detail/detail-index';

        // 准备SEO信息
        $seoTitle       = $goods->seo_title ?: $goods->getData('name');
        $seoKeywords    = $goods->seo_keywords ?: $goods->getData('name');
        $seoDescription = $goods->seo_description ?: (mb_substr(strip_tags($goods->content), 0, 200) . '...');

        return $this->render($template, [
            'title'             => $seoTitle ?? $goods->getData('name'),
            'keywords'          => $seoKeywords,
            'description'       => $seoDescription,
            'goods'             => $goods,
            'related_goods'     => $relatedGoods,
            'comments'          => $comments,
            'comments_total'    => $total,
            'comments_per_page' => $per_page,
            'comments_page'     => $current_page,
            'comments_has_more' => $has_more,
        ]);
    }

    /**
     * 商品分类页
     */
    public function category()
    {
        $id     = $this->request->route->param('id');
        $pinyin = $this->request->route->param('pinyin');
        if (!$id && !$pinyin) {
            return $this->render('404', ['title' => '分类不存在']);
        }
        $page         = $this->request->get('page', 1);
        $sort         = $this->request->get('sort', 'default');
        $price_range  = $this->request->get('price_range', '');
        $type         = $this->request->get('type', ''); // 资源类型筛选
        $spec_filters = $this->request->get('spec_filters', []);

        // 获取分类信息
        if ($pinyin) {
            $category = GoodsCategoryModel::where([
                'status' => 1,
                'pinyin' => $pinyin
            ])->find();
        } else {
            $category = GoodsCategoryModel::where([
                'status' => 1,
                'id'     => $id
            ])->find();
        }

        if (!$category) {
            return $this->render('404', ['title' => '分类不存在']);
        }

        // 获取分类ID
        $id = $category->id;

        // 生成多筛选URL参数
        $filterParams = $this->buildFilterParams($type, $price_range, $sort);
        $filterUrls   = $this->buildFilterUrls($filterParams);

        // 获取所有一级分类
        $all_categories = GoodsCategoryModel::where([
            'status'  => 1,
            'pid'     => 0,
            'is_menu' => 1
        ])->order('sort desc, id desc')->field('id,name,pinyin')->select();

        // 获取当前分类的子分类（如果当前是一级分类）
        $current_category_children = [];
        if ($category->pid == 0) {
            // 当前是一级分类，获取其子分类
            $current_category_children = GoodsCategoryModel::where([
                'status' => 1,
                'pid'    => $id
            ])->order('sort desc, id desc')->field('id,name,pinyin')->select();
        } else {
            // 当前是子分类，获取同级分类
            $current_category_children = GoodsCategoryModel::where([
                'status' => 1,
                'pid'    => $category->pid
            ])->order('sort desc, id desc')->field('id,name,pinyin')->select();
        }

        // 获取子分类（保持原有逻辑）
        $children = $this->getChildren($id);

        // 获取规格筛选字段
        $specFilters = $this->getSpecFilter($id);

        // 获取商品列表
        $goodsList = $this->getCategoryGoodsList($id, $spec_filters, $page, $sort, $price_range, $type);

        // 检查是否是AJAX请求
        if ($this->request->get('ajax')) {
            return $this->success('获取成功', [
                'goods_list'   => $goodsList['list'],
                'total'        => $goodsList['total'],
                'current_page' => $page,
                'per_page'     => $this->limit,
                'has_more'     => $goodsList['total'] > $page * $this->limit
            ]);
        }

        // 使用分类的模板字段，如果为空则使用默认模板
        $template = $category->template ?: 'goods/category/category-index';

        // 获取父分类（用于面包屑导航）
        $parent_category = null;
        if ($category->pid > 0) {
            $parent_category = GoodsCategoryModel::where(['id' => $category->pid, 'status' => 1])->field('id,name,pinyin')->find();
        }

        // 准备SEO信息
        $seoTitle       = $category->seo_title ?: $category->getData('name');
        $seoKeywords    = $category->seo_keywords ?: $category->getData('name');
        $seoDescription = $category->seo_description ?: ($category->getData('name') . ' - ' . conf('site_name'));

        return $this->render($template, array_merge([
            'title'                     => $seoTitle,
            'keywords'                  => $seoKeywords,
            'description'               => $seoDescription,
            'category'                  => $category,
            'parent_category'           => $parent_category,
            'children'                  => $children,
            'all_categories'            => $all_categories,
            'current_category_children' => $current_category_children,
            'current_category_id'       => $id,
            'spec_filters'              => $specFilters,
            'goods_list'                => $goodsList['list'],
            'total'                     => $goodsList['total'],
            'current_page'              => $page,
            'per_page'                  => $this->limit,
            'current_sort'              => $sort,
            'current_price_range'       => $price_range,
            'current_spec_filters'      => $spec_filters,
            'current_category'          => $id,
            'current_type'              => $type,
        ], $filterUrls));
    }

    /**
     * 搜索结果页
     */
    public function search()
    {
        $keyword = $this->request->route->param('keyword') ?: $this->request->get('keyword', '');
        $page    = $this->request->get('page', 1);
        $sort    = $this->request->get('sort', 'relevance');

        if (!$keyword) {
            // 如果是AJAX请求
            if ($this->request->isAjax()) {
                return json([
                    'code' => 0,
                    'msg'  => '搜索关键词不能为空',
                    'data' => []
                ]);
            }

            // 获取热门
            $hotBooks = GoodsModel::where('status', 1)
                ->order('views desc, id desc')
                ->limit(20)
                ->select();

            return $this->render('goods/search', [
                'title'     => '搜索结果',
                'keyword'   => '',
                'goods'     => [],
                'total'     => 0,
                'hot_books' => $hotBooks,
            ]);
        }

        // 搜索商品
        $query = GoodsModel::where('status', 1)
            ->where('name', 'like', '%' . $keyword . '%');

        // 排序
        switch ($sort) {
            case 'price_asc':
                $query->order('price asc, id desc');
                break;
            case 'price_desc':
                $query->order('price desc, id desc');
                break;
            case 'time_desc':
                $query->order('create_time desc, id desc');
                break;
            case 'relevance':
            default:
                $query->order('sort desc, id desc');
                break;
        }

        $total     = $query->count();
        $goodsList = $query->page($page, $this->limit)->select()->each(function ($item) {
            $item->url   = _url_('goods/detail', ['id' => $item->id]);
            $item->views = format_view_count($item->views);
        });


        // 如果是AJAX请求，返回JSON数据
        if ($this->request->isAjax()) {
            return json([
                'code' => 1,
                'msg'  => 'success',
                'data' => [
                    'goods_list'   => $goodsList,
                    'total'        => $total,
                    'current_page' => $page,
                    'per_page'     => $this->limit,
                    'total_pages'  => ceil($total / $this->limit)
                ]
            ]);
        }

        // 如果没有搜索结果，获取热门书籍
        $hotBooks = [];
        if (count($goodsList) == 0) {
            $hotBooks = GoodsModel::where('status', 1)
                ->order('views desc, id desc')
                ->limit(20)
                ->select();
        }

        return $this->render('goods/search', [
            'title'        => '搜索: ' . $keyword,
            'keyword'      => $keyword,
            'goods'        => $goodsList,
            'goods_list'   => $goodsList,
            'total'        => $total,
            'current_page' => $page,
            'per_page'     => $this->limit,
            'hot_books'    => $hotBooks,
            'page_info'    => [
                'total'        => $total,
                'per_page'     => $this->limit,
                'current_page' => $page,
                'total_pages'  => ceil($total / $this->limit),
            ],
        ]);
    }

    /**
     * 商品标签页
     */
    public function tag()
    {
        $tag_id = $this->request->get('tag_id');
        $page   = $this->request->get('page', 1);

        // 获取所有标签
        $tags = GoodsTagModel::order('sort desc, id desc')->select();

        $goodsList  = [];
        $total      = 0;
        $currentTag = null;

        if ($tag_id) {
            $currentTag = GoodsTagModel::where(['id' => $tag_id])->find();
            if ($currentTag) {
                // 获取标签下的商品
                $query = GoodsModel::where('status', 1)
                    ->where('tag_ids', 'like', '%,' . $tag_id . ',%')
                    ->order('sort desc, id desc');

                $total     = $query->count();
                $goodsList = $query->page($page, $this->limit)->select()->each(function ($item) {
                    $item->url   = _url_('goods/detail', ['id' => $item->id]);
                    $item->views = format_view_count($item->views);
                });
            }
        }

        // 如果是AJAX请求，返回JSON数据
        if ($this->request->isAjax()) {
            return json([
                'code' => 1,
                'msg'  => 'success',
                'data' => [
                    'goods_list'   => $goodsList,
                    'total'        => $total,
                    'current_page' => $page,
                    'per_page'     => $this->limit,
                    'has_more'     => $total > $page * $this->limit
                ]
            ]);
        }

        return $this->render('goods/tag', [
            'title'        => $currentTag ? $currentTag->name : '商品标签',
            'tags'         => $tags,
            'current_tag'  => $currentTag,
            'goods_list'   => $goodsList,
            'total'        => $total,
            'current_page' => $page,
            'per_page'     => $this->limit,
        ]);
    }

    /**
     * 标签详情页
     */
    public function tagDetail()
    {
        $id   = $this->request->route->param('id');
        $page = $this->request->get('page', 1);

        if (!$id) {
            return $this->render('404', ['title' => '标签不存在']);
        }

        // 获取标签信息
        $tag = GoodsTagModel::where(['id' => $id])->find();
        if (!$tag) {
            return $this->render('404', ['title' => '标签不存在']);
        }

        // 获取标签下的商品（使用关联表查询）
        $query = GoodsModel::alias('g')
            ->join('goods_tag_relation gtr', 'g.id = gtr.goods_id')
            ->where('g.status', 1)
            ->where('gtr.tag_id', $id)
            ->order('g.sort desc, g.id desc');

        $total     = $query->count();
        $goodsList = $query->field('g.*')->page($page, $this->limit)->select();

        // 如果是AJAX请求，返回JSON数据
        if ($this->request->isAjax()) {
            return json([
                'code' => 1,
                'msg'  => 'success',
                'data' => [
                    'goods_list'   => $goodsList,
                    'total'        => $total,
                    'current_page' => $page,
                    'per_page'     => $this->limit,
                    'has_more'     => $total > $page * $this->limit
                ]
            ]);
        }
        $tags = GoodsTagModel::order('sort desc, id desc')->limit(10)->select();

        return $this->render('goods/tag', [
            'title'        => $tag->name . ' - 标签',
            'current_tag'  => $tag,
            'goods_list'   => $goodsList,
            'tags'         => $tags,
            'total'        => $total,
            'current_page' => $page,
            'per_page'     => $this->limit,
        ]);
    }

    /**
     * 章节内容页
     */
    public function chapter()
    {
        $chapter_id = $this->request->route->param('id');

        if (!$chapter_id) {
            return $this->render('404', ['title' => '章节不存在']);
        }

        // 获取章节信息
        $chapter = \app\common\model\GoodsContentChapter::where([
            'id' => $chapter_id
        ])->find();

        if (!$chapter) {
            return $this->render('404', ['title' => '章节不存在']);
        }

        // 获取商品信息
        $goods = GoodsModel::where([
            'status' => 1,
            'id'     => $chapter->goods_id
        ])->find();

        if (!$goods) {
            return $this->render('404', ['title' => trans('goods_not_exists')]);
        }

        if (!$chapter) {
            return $this->render('404', ['title' => '章节不存在']);
        }

        // 检查用户权限
        $hasAuth = false;
        if ($this->user_id) {
            // 检查是否已购买商品
            $hasAuth = (new \app\common\model\User())->canViewContent($chapter->goods_id);
        }

        // 如果章节免费或商品免费，则有权限
        if ($chapter->is_free || !$goods->price) {
            $hasAuth = true;
        }

        // 处理长文本内容
        if ($chapter->resource_type == 'longtext' && $hasAuth) {
            $textContentService        = new \app\service\goods\TextContentService();
            $chapter->longtext_content = $textContentService->getChapterText(
                $chapter->id,
                $goods->id,
                $goods->cate_id,
                $hasAuth
            );
        }

        // 根据资源类型渲染不同的模板
        $template = $this->getChapterTemplate($chapter->resource_type);
        return $this->render($template, [
            'title'    => $chapter->getData('title') . ' - ' . $goods->getData('name'),
            'goods'    => $goods,
            'chapter'  => $chapter,
            'has_auth' => $hasAuth,
        ]);
    }

    /**
     * 根据资源类型获取对应的模板
     */
    private function getChapterTemplate($resourceType)
    {
        switch ($resourceType) {
            case 'cloud':
                return 'goods/chapter/cloud';
            case 'text':
                return 'goods/chapter/text';
            case 'video':
                return 'goods/chapter/video';
            case 'audio':
                return 'goods/chapter/audio';
            case 'longtext':
                return 'goods/chapter/longtext';
            default:
                return 'goods/chapter/text';
        }
    }

    /**
     * 获取子分类
     */
    private function getChildren($parentId)
    {
        return GoodsCategoryModel::where([
            'status' => 1,
            'pid'    => $parentId
        ])->field('id,name,pic,is_spec_filter,pinyin')->order('sort desc, id desc')->select()->each(function ($child) {
            $child->goods_count = $child->goods()->where(['status' => 1])->count();
            $child->children    = $this->getChildren($child->id);
            $child->url         = _url_('goods.category', ['pinyin' => $child->pinyin]);
        });
    }

    /**
     * 获取相关商品
     */
    private function getRelatedGoods($cateId, $excludeId, $limit = 8)
    {
        $relatedGoods = GoodsModel::where([
            'status'  => 1,
            'cate_id' => $cateId
        ])->where('id', '<>', $excludeId)->order('sort desc, id desc')->limit($limit)->select();

        return $relatedGoods;
    }

    /**
     * 获取分类商品列表
     */
    private function getCategoryGoodsList($cateId, $specFilters = [], $page = 1, $sort = 'default', $priceRange = '', $type = '')
    {
        // 获取当前分类及所有子分类的ID
        $cateIds = $this->getAllCateIds($cateId);

        $query = GoodsModel::where(['status' => 1])->whereIn('cate_id', $cateIds);

        // 价格区间筛选
        if (!empty($priceRange)) {
            switch ($priceRange) {
                case '0-50':
                    $query->where('price', '>=', 0)->where('price', '<=', 50);
                    break;
                case '50-100':
                    $query->where('price', '>', 50)->where('price', '<=', 100);
                    break;
                case '100-200':
                    $query->where('price', '>', 100)->where('price', '<=', 200);
                    break;
                case '200+':
                    $query->where('price', '>', 200);
                    break;
            }
        }

        // 资源类型筛选
        if (!empty($type)) {
            switch ($type) {
                case 'free':
                    // 免费课程：价格为0
                    $query->where('price', '=', 0);
                    break;
                case 'paid':
                    // 付费课程：价格大于0且不是VIP专享
                    $query->where('price', '>', 0);
                    break;
                case 'vip':
                    // VIP专享：标记为VIP专享的商品
                    $query->where('is_vip_exclusive', '=', 1);
                    break;
            }
        }

        // 如果有规格筛选条件
        if (!empty($specFilters)) {
            $query->alias('g')->join('goods_spec_relation r', 'g.id = r.goods_id');

            foreach ($specFilters as $field => $value) {
                if (empty($value))
                    continue;
                $query->where("JSON_EXTRACT(r.spec_value, '$." . $field . "') LIKE '%" . $value . "%'");
            }
        }

        // 排序
        switch ($sort) {
            case 'price_asc':
                $orderBy = 'price asc, id desc';
                break;
            case 'price_desc':
                $orderBy = 'price desc, id desc';
                break;
            case 'sales_desc':
                $orderBy = 'sales_volume desc, id desc';
                break;
            case 'time_desc':
                $orderBy = 'create_time desc, id desc';
                break;
            default:
                $orderBy = 'sort desc, id desc';
                break;
        }

        $total = $query->count();

        if (!empty($specFilters)) {
            $list = $query->order($orderBy)->field('g.*')->page($page, $this->limit)->select()->each(function ($item) {
                $item->url   = _url_('goods/detail', ['id' => $item->id]);
                $item->views = format_view_count($item->views);
            });
        } else {
            $list = $query->order($orderBy)->page($page, $this->limit)->select()->each(function ($item) {
                $item->url   = _url_('goods/detail', ['id' => $item->id]);
                $item->views = format_view_count($item->views);
            });
        }

        return ['list' => $list, 'total' => $total];
    }

    /**
     * 获取分类及其所有子分类ID
     */
    private function getAllCateIds($cateId)
    {
        $ids = [$cateId];

        $children = GoodsCategoryModel::where([
            'status' => 1,
            'pid'    => $cateId
        ])->column('id');

        foreach ($children as $childId) {
            $ids = array_merge($ids, $this->getAllCateIds($childId));
        }

        return $ids;
    }

    /**
     * 获取分类的规格筛选字段
     */
    private function getSpecFilter($cateId)
    {
        $category = GoodsCategoryModel::where('id', $cateId)->where('status', 1)->find();

        if (!$category) {
            return [];
        }

        $result = [];

        // 处理规格筛选字段
        if ($category->is_spec_filter && $category->spec_id) {
            $spec = GoodsSpec::where('id', $category->spec_id)->where('status', 1)->find();
            if ($spec) {
                $spec_data  = $spec->toArray();
                $rule_value = $spec_data['rule_value'] ?? [];

                if (is_array($rule_value)) {
                    foreach ($rule_value as $field) {
                        if (isset($field['type']) && $field['type'] == 'select' && !empty($field['detail'])) {
                            $result[] = [
                                'spec_id'     => $spec->getData('id'),
                                'spec_name'   => $spec->getData('name'),
                                'field_name'  => $field['value'],
                                'field_label' => $field['label'],
                                'options'     => $field['detail'],
                                'filter_type' => 'spec',
                            ];
                        }
                    }
                }
            }
        }

        // 处理额外的检索条件
        $search_filters = $category->search_filters;
        if (!empty($search_filters) && is_array($search_filters)) {
            foreach ($search_filters as $filter) {
                if (!empty($filter['title']) && !empty($filter['value']) && !empty($filter['bind_search'])) {
                    $options = explode(',', $filter['value']);
                    $options = array_map('trim', $options);

                    $result[] = [
                        'field_name'  => $filter['bind_search'],
                        'field_label' => $filter['title'],
                        'options'     => $options,
                        'filter_type' => 'custom',
                    ];
                }
            }
        }

        return $result;
    }

    /**
     * 获取商品规格信息 - 参考API实现
     */
    private function getGoodsSpecInfo($goodsId)
    {
        $goods = GoodsModel::where('id', $goodsId)->find();
        if (!$goods) {
            return [];
        }

        // 获取商品分类的规格
        $rule_value = $goods?->category?->spec?->rule_value;
        // 获取商品关联规格
        $goods_spec = $goods?->goodsSpec?->spec_value;

        // 正确处理规格信息
        $spec_info = [];
        if ($rule_value && $goods_spec) {
            foreach ($rule_value as $item) {
                if (isset($goods_spec[$item['value']])) {
                    $spec_info[] = [
                        'label' => $item['label'],
                        'value' => $goods_spec[$item['value']]
                    ];
                }
            }
        }

        return $spec_info;
    }

    /**
     * 增加商品浏览量
     */
    private function incrementViews($goodsId)
    {
        GoodsModel::where('id', $goodsId)->inc('views', 1)->save();
    }

    /**
     * 检查商品收藏状态
     */
    private function checkFavoriteStatus($goodsId)
    {
        if (!$this->user_id) {
            return false;
        }

        $favorite = UserFavorite::where([
            'user_id'     => $this->user_id,
            'relation_id' => $goodsId
        ])->find();

        return $favorite ? true : false;
    }

    /**
     * 获取默认评论数据（用于SEO）
     */
    private function getDefaultComments($goodsId, $limit = 5)
    {
        $query = \app\common\model\GoodsComment::with(['user' => function ($query) {
            $query->field('id,username,avatar,nickname');
        },
            'replies' => function ($query) {
                $query->with(['user' => function ($subQuery) {
                    $subQuery->field('id,username,avatar,nickname');
                }
                ])->where('status', \app\common\model\GoodsComment::STATUS_APPROVED)
                    ->field('id,goods_id,user_id,content,parent_id,create_time,update_time,likes')
                    ->order('create_time', 'asc')
                    ->limit(3); // 每个评论最多显示3条回复
            }
        ])
            ->where([
                'goods_id'  => $goodsId,
                'status'    => \app\common\model\GoodsComment::STATUS_APPROVED,
                'parent_id' => 0  // 只查询一级评论
            ])
            ->field('id,goods_id,user_id,content,parent_id,create_time,update_time,likes')
            ->order('create_time', 'asc');

        $total    = $query->count();
        $comments = $query->limit($limit)->select();

        // 处理评论数据
        $comments->each(function ($item) {
            // 检查当前用户是否点赞了这条评论
            if ($this->user_id) {
                $item->is_liked = \app\common\model\CommentLike::where([
                    'user_id'    => $this->user_id,
                    'comment_id' => $item->id
                ])->count() > 0;
            } else {
                $item->is_liked = false;
            }

            // 处理内容中的图片和附件
            $this->processCommentContent($item);

            // 处理回复数据
            if ($item->replies) {
                $item->replies->each(function ($reply) {
                    // 检查当前用户是否点赞了这条回复
                    if ($this->user_id) {
                        $reply->is_liked = \app\common\model\CommentLike::where([
                            'user_id'    => $this->user_id,
                            'comment_id' => $reply->id
                        ])->count() > 0;
                    } else {
                        $reply->is_liked = false;
                    }

                    // 处理回复内容中的图片和附件
                    $this->processCommentContent($reply);
                });
            }
        });

        return [
            'list'     => $comments,
            'total'    => $total,
            'has_more' => $total > $limit
        ];
    }

    /**
     * 处理评论内容中的图片和附件
     */
    private function processCommentContent($comment)
    {
        if (!$comment->content) {
            return;
        }

        // 提取并移除图片标签
        $imgRegex = '/<img[^>]+src="([^"]+)"[^>]*>/';
        preg_match_all($imgRegex, $comment->content, $imgMatches);
        if (!empty($imgMatches[1])) {
            $comment->images  = $imgMatches[1];
            $comment->content = preg_replace($imgRegex, '', $comment->content);
        }

        // 提取并移除文件链接
        $fileRegex = '/<a[^>]+href="([^"]+)"[^>]*data-type="file"[^>]*>([^<]+)<\/a>/';
        preg_match_all($fileRegex, $comment->content, $fileMatches);
        if (!empty($fileMatches[1])) {
            $attachments = [];
            for ($i = 0; $i < count($fileMatches[1]); $i++) {
                $attachments[] = [
                    'url'  => $fileMatches[1][$i],
                    'name' => $fileMatches[2][$i],
                    'type' => 'file'
                ];
            }
            $comment->attachments = $attachments;
            $comment->content     = preg_replace($fileRegex, '', $comment->content);
        }

        // 清理内容中的多余空白
        $comment->content = trim($comment->content);
    }

    /**
     * 构建筛选参数
     */
    private function buildFilterParams($type, $price_range, $sort)
    {
        $params = [];

        if ($type) {
            $params['type'] = $type;
        }

        if ($price_range) {
            $params['price_range'] = $price_range;
        }

        if ($sort && $sort !== 'default') {
            $params['sort'] = $sort;
        }

        return $params;
    }

    /**
     * 构建筛选URL
     */
    private function buildFilterUrls($currentParams)
    {
        $urls = [];

        // 不包含分类的筛选参数
        $withoutCategory                          = $currentParams;
        $urls['current_filters_without_category'] = $withoutCategory ? '?' . http_build_query($withoutCategory) : '';

        // 不包含类型的筛选参数
        $withoutType = $currentParams;
        unset($withoutType['type']);
        $urls['current_filters_without_type'] = $withoutType ? '?' . http_build_query($withoutType) : '';

        // 包含免费类型的筛选参数
        $withTypeFree                           = $currentParams;
        $withTypeFree['type']                   = 'free';
        $urls['current_filters_with_type_free'] = '?' . http_build_query($withTypeFree);

        // 包含付费类型的筛选参数
        $withTypePaid                           = $currentParams;
        $withTypePaid['type']                   = 'paid';
        $urls['current_filters_with_type_paid'] = '?' . http_build_query($withTypePaid);

        // 不包含价格的筛选参数
        $withoutPrice = $currentParams;
        unset($withoutPrice['price_range']);
        $urls['current_filters_without_price'] = $withoutPrice ? '?' . http_build_query($withoutPrice) : '';

        // 包含不同价格区间的筛选参数
        $priceRanges = ['0-50', '50-100', '100-200', '200+'];
        foreach ($priceRanges as $range) {
            $withPrice                = $currentParams;
            $withPrice['price_range'] = $range;
            $key                      = 'current_filters_with_price_' . str_replace(['-', '+'], ['_', ''], $range);
            $urls[$key]               = '?' . http_build_query($withPrice);
        }

        // 包含不同排序的筛选参数
        $sorts = ['default', 'price_asc', 'price_desc', 'sales', 'newest'];
        foreach ($sorts as $sortType) {
            $withSort = $currentParams;
            if ($sortType === 'default') {
                unset($withSort['sort']);
            } else {
                $withSort['sort'] = $sortType;
            }
            $key        = 'current_filters_with_sort_' . $sortType;
            $urls[$key] = $withSort ? '?' . http_build_query($withSort) : '';
        }

        return $urls;
    }

    /**
     * 获取分类列表API - 直接调用API项目逻辑
     */
    public function categories()
    {
        try {
            // 使用与API项目相同的逻辑获取分类数据
            $categories = GoodsCategoryModel::where([
                'status'  => 1,
                'pid'     => 0,
                'is_menu' => 1
            ])->order('sort desc, id desc')->field('id,name,pic,is_spec_filter,pinyin')->select();

            $list = [];
            foreach ($categories as $category) {
                $children = $this->getChildren($category['id']);
                $list[]   = [
                    'id'       => $category['id'],
                    'name'     => $category['name'],
                    'pic'      => $category['pic'],
                    'children' => $children,
                    'url'      => _url_('goods.category', ['pinyin' => $category['pinyin']])
                ];
            }

            return json([
                'code' => 1,
                'msg'  => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg'  => '获取分类失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }
}
